<template>
  <div class="app-container">
    <FormRecordFilter
      :percentage="percentage"
      :show-down-percentage="showDownPercentage"
      :down-load-loading="downLoadLoading"
      @on-filter="submitFilterForm"
      @on-export="exportFilterForm"/>

    <el-table
      :data="tableData.list"
      height="500"
      v-loading="loading"
      element-loading-text="加载中..."
      show-summary
      border
      :summary-method="getLocalSummaries"
      class="el-table-align-center"
    >
      <!--<el-table-column width="50" label="序号" type="index" align="center">-->
      <!--</el-table-column>-->
      <el-table-column :label="$t('language.finance.recharge.rechargeTime')" width="90" align="center">
        <template slot-scope="{row}">
          <div>{{row.createDate | toTime}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.rechargeNumber')" width="120" align="center">
        <template slot-scope="{row}">
          <div>{{row.orderId}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.thirdPartyRechargeOrderNumber')"  width="120" align="center">
        <template slot-scope="{row}">
          <div>{{row.thirdOrderId}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.accountType')" prop="userType" align="center">
        <template slot-scope="{row}">
<!--          {{getLabel(row.userType, payEnum.USER_TYPE)}}-->
          {{toSwitchData('language.finance.consts.USER_TYPE', row.userType)}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.level')" prop="userLevel" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.accountName')" prop="username" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.name')" prop="reallyName" align="center">
      </el-table-column>
      <el-table-column sortable :label="$t('language.finance.recharge.depositAmount')"  prop="amount" width="100" align="center">
        <template slot-scope="{row}">
          {{row.amount | currency}}
        </template>
      </el-table-column>
      <el-table-column sortable :label="$t('language.finance.recharge.handlingFee')" prop="fee" width="90" align="center">
        <template slot-scope="{row}">
          {{row.fee | currency('', 2, {type: 1})}}
        </template>
      </el-table-column>
       <el-table-column sortable :label="$t('language.finance.recharge.actualAmount')" width="100" prop="payAmount" align="center">
        <template slot-scope="{row}">
          {{row.payAmount | currency}}
        </template>
      </el-table-column>
      <!--<el-table-column label="附言" prop="keyword" align="center">-->
      <!--</el-table-column>-->
      <el-table-column :label="$t('language.finance.recharge.operatingTime')" width="90" align="center">
        <template slot-scope="{row}">
          {{row.createDate | toTime}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.depositType')" width="90" align="center">
        <template slot-scope="{row}">
<!--          {{getLabel(row.limitType, payEnum.DEPOSIT_TYPE)}}-->
          {{toSwitchData('language.finance.consts.DEPOSIT_TYPE', row.limitType)}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.paymentStatus')"  align="center">
        <template slot-scope="{row}">
<!--          {{row.subStatus | toConverter('PAYMENT_SUB_STATUS') }}-->
          <span v-if="row.status==1||row.status==2">{{toSwitchData('language.finance.consts.PAYMENT_SUB_STATUS',row.subStatus)}}</span>
          <span v-else>{{toSwitchData('language.finance.consts.PAYMENT_STATUS_BACK', row.status)}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.paymentTypes')" align="center">
        <template slot-scope="{row}">
<!--          {{row.paymentId | toConverter('RECHARGE_TYPE_NAMES')}}-->
          {{toSwitchData('language.finance.consts.RECHARGE_THIRD_TYPE_NAMES', row.paymentId)}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.receiptMerchant')" width="100"  align="center">
        <template slot-scope="{row}">
          <div>{{row.merchantName }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.receiptMerchantNumber')" width="150"  align="center">
        <template slot-scope="{row}">
          <div>{{row.merchantCode }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.arrivalTime')" prop="addTime" width="90" align="center">
        <template slot-scope="{row}">
          <div v-if="row.sucApvTime">{{row.sucApvTime | toTime}}</div>
          <div v-else>{{row.payTime | toTime}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.patchUpVerifier')" prop="sucApvOperator" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.verifiedTime')" align="center">
        <template slot-scope="{row}">
          <div>{{row.sucApvTime | toTime}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.withdrawal.operationEnd')"  align="center">
        <template slot-scope="{row}">
          {{row.clientType | toConverter('PAYMENT_PLATFORM') }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('language.finance.recharge.remarks')" prop="sucReqRemark" align="center">
      </el-table-column>
      <el-table-column :label="$t('language.table.actions')" fixed="right" width="80" align="center">
        <template slot-scope="{row}">
          <!--<el-button type="warning" size="mini" @click="openDialog({dialogName: 'apply-reorder-dialog', props: row })"-->
                     <!--v-if="row.status!=3 && roleCheck('auto-repair')">补单-->
          <!--</el-button>-->
          <el-button
            type="text"
            size="mini"
            @click="openDialog({dialogName: dialogType.applyReorder, props: row })"
            v-if=" row.subStatus == 2 || row.subStatus == 3 || row.subStatus == 4 "
          >
            {{$t('language.finance.recharge.check')}}
          </el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="gridSizeChange"
        @current-change="gridCurrentChange"
        :current-page="filters.page"
        :page-sizes="gridPageSize"
        :page-size="filters.size"
        :layout="gridLayout"
        :total="tableData.total"
      >
      </el-pagination>
    </div>
    <ApplyReorderDialog
      v-if="dialogName === dialogType.applyReorder"
      :row-data="dialogProps"
      v-model="dialogVisible"
      :id="dialogProps.id"
      :is-check="true"
      @submit="submitFinished"
    />
  </div>
</template>


<script>

// components
import FormRecordFilter from './formRecordFilter';
import ApplyReorderDialog from './applyReorderDialog';

// mixins
import {
  grid, constsLabel, dialog, switchData,
} from '@/build';

// services
import { getRechargeLogs, exportThirdCharge } from '@/services/api/recharge';

const dialogType = {
  applyReorder: 'apply-reorder-dialog',
};

export default {
  name: 'recharge-logs',
  components: {
    FormRecordFilter,
    ApplyReorderDialog,
  },
  mixins: [grid, constsLabel, dialog, switchData],
  data() {
    return {
      tableData: {
        list: [],
        glRechargeAllCollect: {
          arrivalAmountCollect: 0,
          depositAmountCollect: 0,
          handlingFeeAmountCollect: 0,
        },
        total: 0,
      },
      rowData: {},
      filters: {
        page: 1,
        size: 20,
        dateType: 1,
        searchType: 1,
        paymentId: -2,
        limitType: -1,
        status: '0,3',
        subStatus: '6,5,4,3,2,1',
        startTime: moment().format('YYYY-MM-DD 00:00:00'),
        endTime: moment().format('YYYY-MM-DD 23:59:59'),
        userType: -1,
      },
      filterDateType: false,
      dialogType,
      statistic: [
        {
          index: 3,
          prop: '',
          format: () => '',
        },
        {
          index: 4,
          prop: '',
          format: () => '',
        },
        {
          index: 5,
          prop: '',
          format: () => '',
        },
        {
          index: 6,
          prop: '',
          format: () => '',
        },
        {
          index: 16,
          prop: '',
          format: () => '',
        },
        {
          index: 20,
          prop: '',
          format: () => '',
        },
        {
          index: 7,
          prop: 'amount',
          format: value => `${_.currency(value)}/ ${_.currency(this.tableData.glRechargeAllCollect.depositAmountCollect)}`,
          // format: value => <div>{_.currency(value)}/{_.currency(this.tableData.glRechargeAllCollect.depositAmountCollect)}</div>,
        },
        {
          index: 8,
          prop: 'fee',
          format: value => `${_.currency(value, '', 2, { type: 1 })}/ ${_.currency(this.tableData.glRechargeAllCollect.handlingFeeAmountCollect)}`,
        },
        {
          index: 9,
          prop: 'payAmount',
          format: value => `${_.currency(value)}/ ${_.currency(this.tableData.glRechargeAllCollect.arrivalAmountCollect)}`,
        },
      ],
      localSummariesText: '当前页汇总 / 所有页汇总',
      percentage: 0,
      showDownPercentage: false,
      exportData: [],
      downLoadLoading: false,
    };
  },
  methods: {
    async exportHandle(page = 1) {
      const {
        dateType, userType, status, searchType, paymentId,
        limitType, fromDate, endDate, time, minAmount, maxAmount,
        merchant, keywords, payStatus, clientType, startTime, endTime,
      } = this.filters;
      const size = 1000;
      const ajaxData = {
        dateType,
        userType,
        status,
        searchType,
        paymentId,
        limitType,
        fromDate,
        endDate,
        time,
        minAmount,
        maxAmount,
        merchant,
        keywords,
        payStatus,
        clientType,
        startTime,
        endTime,
        page,
        size,
      };
      const filename = '第三方充值明细报表.csv';
      // const header = ['充值时间', '充值单号', '第三方充值单号', '账户类型', '层级', '账户名', '姓名', '存款金额', '手续费', '到账金额', '操作时间', '存款类型', '支付状态', '支付类型', '收款商户', '收款商户号', '到账时间', '补单审核人', '审核时间', '操作端', '备注'];
      // const filterField = ['createDate', 'orderId', 'thirdOrderId', 'userType', 'userLevel', 'username', 'reallyName', 'amount', 'fee', 'payAmount', 'createDate', 'limitType', 'subStatus', 'paymentId', 'channelName', 'merchantCode', 'payTime', 'sucApvOperator', 'sucApvTime', 'clientType', 'sucReqRemark'];
      const header = ['充值时间', '充值单号', '层级', '账户名', '姓名', '存款金额', '手续费', '到账金额', '附言', '到账时间', '收款商户', '收款商户号', '收款银行', '收款人姓名', '支付状态'];
      const filterField = ['createDate', 'orderId', 'userLevel', 'username', 'reallyName', 'amount', 'fee', 'payAmount', 'keyword', 'payTime', 'merchantName', 'merchantCode', 'bankName', 'cardUsername', 'payStatus'];
      // exportThirdCharge(ajaxData).then(([result, data]) => {
      //   if (result) {
      //     const exportData = this.responseFormatter(data.list);
      //     this.export2Excel(header, filterField, exportData, filename);
      //   } else {
      //     this.$message({ message: `导出失败,${data.message}`, type: 'warning' });
      //   }
      // });
      this.showDownPercentage = true;
      this.downLoadLoading = true;
      const [result, data] = await exportThirdCharge(ajaxData);
      if (result) {
        if (data && data.list.length > 0) {
          const allPage = Math.ceil(data.total / size);
          this.exportData = [...this.exportData, ...this.responseFormatter(data.list)];
          this.percentage = (page / allPage).toFixed(2) * 100;
          if (page < allPage) {
            this.exportHandle(page + 1);
          } else {
            this.export2Excel(header, filterField, this.exportData, filename);
            this.exportData = [];
            setTimeout(() => {
              this.initDownLoad();
            }, 1000);
          }
        } else {
          this.$message({ message: '导出内容为空，请重新选择', type: 'warning' });
          this.initDownLoad();
        }
      } else {
        this.$message({ message: `导出失败,${data.message}`, type: 'warning' });
        this.initDownLoad();
      }
    },
    initDownLoad() {
      this.showDownPercentage = false;
      this.percentage = 0;
      this.downLoadLoading = false;
    },
    responseFormatter(data) {
      data.map((item) => {
        item.amount = _.currency(item.amount);
        item.fee = _.currency(item.fee);
        item.payAmount = _.currency(item.payAmount);
        // item.amountWithoutFee = _.currency(item.amountWithoutFee);
        item.createDate = _.toTime(item.createDate);
        // item.amountWithoutFee = (item.amount - item.fee) < 0 ? 0 : item.amount - item.fee;
        item.payStatus = (item.status === 0 || item.status === 3) ? _.toConverter(item.status, 'PAYMENT_STATUS_BACK')
          : _.toConverter(item.subStatus, 'PAYMENT_SUB_STATUS');
        // item.userType = _.toConverter(item.userType, 'ACCOUNT_TYPE');
        // item.paymentId = _.toConverter(item.paymentId, 'RECHARGE_TYPE_NAMES');
        // item.limitType = item.limitType === 0 ? '普通存款' : '大额存款';
        // item.sucApvTime = _.toTime(item.sucApvTime);
        // item.clientType = _.toConverter(item.clientType, 'PAYMENT_PLATFORM');
        item.payTime = _.toTime(item.sucApvTime ? item.sucApvTime : item.payTime);
      });
      return data;
    },
    submitFilterForm(formInline) {
      const { time } = formInline;
      let startTime;
      let endTime;
      if (!_.isUndefined(time) && _.isArray(time)) {
        startTime = moment(time[0]).format('YYYY-MM-DD HH:mm:ss');
        endTime = moment(time[1]).format('YYYY-MM-DD HH:mm:ss');
        formInline = { ...formInline, startTime, endTime };
      } else {
        this.filters.startTime = undefined;
        this.filters.endTime = undefined;
      }
      if (!formInline.subStatus) {
        delete this.filters.subStatus;
      }

      this.filters = { ...this.filters, ...formInline };
      this.gridSearch();
    },
  },
  mounted() {
    // tab页记录访问日志
    this.$store.dispatch(types.SAVE_OPERATION_LOG, { content: _.getContent(this.$route, '充值记录-第三方充值', true) });
    this.bindGet(getRechargeLogs, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
      beforeSend: (data) => {
        delete data.time;
        if (Array.isArray(data.status)) {
          delete data.status;
        }
        return data;
      },
      format: (data) => {
        data.list.forEach((v) => {
          this.$set(v, 'paragraph', v.amount - v.fee);
        });
        return data;
      },
    });
    this.getAll();
  },
};
</script>

<style scoped lang="scss">
  /deep/ {
    thead .cell{
      word-break: break-word;
    }
    .el-table-align-center{
      .el-table__body-wrapper{
        max-height: 381px;
      }
    }
    .el-table__fixed-right{
      .el-table__fixed-body-wrapper{
        max-height: 381px;
      }
    }
  }
</style>
